<template>
    <div class="memberinfo-layout">
        <div class="info-back bs search-part">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="back-icon" @click="back()">
                        <i class="fa fa-arrow-left" aria-hidden="true"></i>
                    </div>
                </el-col>
                <el-col :span="10" class="btns">
                    <el-button type="primary" class="save red-btn" @click="submitForm('ruleForm')">保存</el-button>

                </el-col>
            </el-row>

        </div>
        <div class="info-form pdt10">

            <el-form :model="ruleForm" :rules="rulesRole" ref="ruleForm" label-width="100px">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>

                <el-form-item label="所属机构：" prop="parentName">
                    <el-input v-model="ruleForm.parentName" v-on:focus="select_organ()"></el-input>
                </el-form-item>

                <!-- <el-form-item label="类型：">
                  <div class="el-left">
                   <el-select v-model="ruleForm.kindCode" placeholder="请选择机构类型">
                     <el-option label="门店" value="10"></el-option>
                     <el-option label="部门" value="20"></el-option>
                     <el-option label="仓库" value="30"></el-option>
                   </el-select>
                 </div>
               </el-form-item> -->

                <el-form-item label="备注：" prop="remark" class="member-mark">
                    <el-input type="textarea" v-model="ruleForm.remark"></el-input>
                </el-form-item>

                <el-form-item label="上传照片：" class="member-upload">
                    <div class="el-left">
                        <el-upload
                                class="avatar-uploader"
                                :action="uploadUrl"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">

                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>


                        </el-upload>
                    </div>
                </el-form-item>


            </el-form>


        </div>
    </div>
</template>


<script scoped>
    import * as type from '../../../store/types';

    export default {
        data: function () {
            return {
                ruleForm: {
                    // kindCode: '10'   //默认为门店10
                    name: '',
                    parentName: '',
                    remark: '',
                    imageUrl: ''
                },
                rulesRole: {},
                id: '',
                selectOrgan: [],
                loading: false,
                uploadUrl: this.$cfg.api_url + "/vue-uploads",
                imageUrl: '',
                result: []
            }
        },

        activated: function () {
            this.$$("#content").scrollTop(0)
            let backInfo = this.$route.params;
            console.log(backInfo)
            this.id = this.$route.query.id;
            if (this.id == undefined) {
                this.id = "";
            }
            //从选择列表进入info
            if (backInfo.flag != undefined) {
                if (backInfo.flag == 'selectOrgan') {
                    console.log("==========>selectOrgan")
                    this.$set(this.ruleForm, 'parentName', backInfo.selected.name);
                    this.$set(this.ruleForm, 'parentId', backInfo.selected.id);
                    console.log(this.ruleForm)
                }
                else if (backInfo.flag == 'selectRoles') {
                    console.log("==========>selectRoles")
                    this.$set(this.ruleForm, 'userRoleNames', backInfo.selected.name);
                    this.$set(this.ruleForm, 'userRoleIds', backInfo.selected.id);
                }
                else if (backInfo.flag == 'back') {
                    console.log("==========>back")
                }
                else {
                    return;
                }


            }
            // 从自身列表页进入
            else {
                if (this.$route.query.new ) {
                    console.log("============>新增");
                    this.ruleForm = {
                      name: '',
                      parentName: '',
                      remark: '',
                      imageUrl: ''
                    };
                    this.imageUrl = '';
                }
                else if(this.id != "") {
                    this.loading = true;
                    var that = this;
                    this.$axioxs.get("/organ/" + this.id)
                        .then(function (res) {
                            console.log(JSON.stringify(res.data));
                            console.log(res.data);
                            that.loading = false;
                            that.ruleForm = res.data;
                            if (that.ruleForm.pictureName) {
                                that.imageUrl = that.$cfg.static_url + "/" + that.ruleForm.pictureName;
                            }
                            else {
                                that.imageUrl = '';
                            }

                            console.log(that.ruleForm);


                        })
                        .catch(function (error) {
                            console.log(error);
                            self.$message({
                                showClose: true,
                                type: 'error',
                                message: error,
                                onClose: function () {
                                    that.loading = false;
                                }
                            });
                        });
                }
                else {
                  console.log("=========>chang tab");
                }
            }


        },

        methods: {
            back: function () {
                this.$store.commit(type.CHANGE_INDEX, '/organ');
                // this.$destroy();
                this.$router.push({
                    path: '/organ'
                });
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(JSON.stringify(this.ruleForm));
                        console.log(this.ruleForm);
                        this.ruleForm.kindCode = 10;
                        this.loading = true;
                        let self = this;
                        this.$axioxs({
                            method: 'post',
                            url: '/organ/',
                            data: this.ruleForm
                        })
                            .then(function (res) {
                                console.log(JSON.stringify(res.data));
                                console.log("===============>sucess")
                                self.loading = false;
                                self.back();

                            })
                            .catch(function (error) {
                                console.log(error);
                                self.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: error,
                                    onClose: function () {
                                        self.loading = false;
                                    }
                                });
                            });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            select_organ: function () {
                console.log(this.ruleForm)
                if (this.ruleForm.parentName) {  //选择仓库时已经有选择的了
                    this.csv2IdNames(this.ruleForm.parentId, this.ruleForm.parentName);
                    console.log(this.result);
                    this.currentSelected = this.result;
                } else {
                    this.currentSelected = [];
                }

                console.log(this.currentSelected)

                this.$router.push({
                    name: 'select',
                    path: '/select/list',
                    query: {id: this.id},
                    params: {
                        toFlag: "selectOrgan",
                        info: this.ruleForm,
                        currentSelected: this.currentSelected,
                        isMultiselect: false,
                        url: "/organ/?states=0,1",
                        backUrl: "/organ/info?id=",
                        backUrlName: "or"
                    }
                });

            },

            csv2IdNames: function (ids, names) {
                console.log(">>>>>>>>>>>>>>>>>>>csv2IdNames");
                console.log(ids);
                console.log(names);
                if (!ids || !names) {
                    return [];
                }

                if (typeof ids != "string" || typeof names != "string") {
                    return [];
                }
                var ids_arr = ids.replace(' ', '').split(',');
                var names_arr = names.replace(' ', '').split(',');

                console.log(ids_arr);
                console.log(names_arr);


                if (ids_arr.length !== names_arr.length) {
                    console.log("长度不一样");
                    return [];
                }


                var result = [];

                for (var i = 0; i < ids_arr.length; i++) {
                    var obj = {};
                    obj.id = (ids_arr[i]).trim();
                    obj.remark = (names_arr[i]).trim();
                    result.push(obj);
                }


                console.log(result);

                this.result = result;


            },

            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                if (res && res.length > 0) {
                    this.ruleForm.pictureId = res[0].id;//将图片实例ID保存在FORM中
                    this.ruleForm.pictureName = res[0].fileName
                }
                console.log(res)
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }

        }
    }

</script>
<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 100%;
        height: auto;
        display: block;
    }

    .memberinfo-tit {
        padding-top: 60px;
    }

</style>
